package GUI;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


import tcpEngine.ConnectInfo;
import tcpEngine.TCPNetworkEngine;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

public class MainGUI extends JFrame implements ActionListener {

	TCPNetworkEngine o;
	TCPNetworkEngine server;
	
	String ip = "127.0.0.1";
	static int port = 8999;
	String userName = "NEXT";
	int type = 0;

	public JTextArea messageShow;
	public JTextArea memberShow;
	JScrollPane messageScrollPane;
	JScrollPane memberScrollPane;

	JLabel messageLabel;
	JLabel nameLabel;

	JTextField clientMessage;
	JButton clientMessageButton;
	JTextField showStatus;


	
	JMenuBar jMenuBar = new JMenuBar();
	JMenu operateMenu = new JMenu("Operation(O)");
	
	JMenuItem userNameItem = new JMenuItem("UserName(I)");
	JMenuItem startgameItem = new JMenuItem("StartGame(L)");
	JMenuItem exitItem = new JMenuItem("Exit(X)");

	JMenu conMenu = new JMenu("Option(C)");
	JMenuItem userItem = new JMenuItem("Users(U)");
	JMenuItem joinItem = new JMenuItem("Join(C)");

	JMenu helpMenu = new JMenu("Help(H)");
	JMenuItem helpItem = new JMenuItem("Help(H)");

	
	JToolBar toolBar = new JToolBar();

	JButton usernameButton;
	JButton startgameButton;
	JButton createServerButton;
	JButton joinButton;
	JButton exitButton;
	JButton findServerButton;


	Dimension faceSize = new Dimension(400, 600);

	JPanel downPanel;
	JPanel midPanel;
	GridBagLayout girdBag;
	GridBagConstraints girdBagCon;

	public MainGUI() {
		init();

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(faceSize);

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation((int) (screenSize.width - faceSize.getWidth()) / 2,
				(int) (screenSize.height - faceSize.getHeight()) / 2);
		this.setResizable(false);
		this.setTitle("Network Game Starter");

		this.setVisible(true);

		operateMenu.setMnemonic('O');
		userNameItem.setMnemonic('I'); 
		startgameItem.setMnemonic('L'); 
		exitItem.setMnemonic('X'); 
		conMenu.setMnemonic('C'); 
		userItem.setMnemonic('U');
		joinItem.setMnemonic('C'); 
		helpMenu.setMnemonic('H');
		helpItem.setMnemonic('H'); 
	}

	public void init() {

		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		operateMenu.add(userNameItem);
		operateMenu.add(startgameItem);
		operateMenu.add(exitItem);
		jMenuBar.add(operateMenu);
		conMenu.add(userItem);
		conMenu.add(joinItem);
		jMenuBar.add(conMenu);
		helpMenu.add(helpItem);
		jMenuBar.add(helpMenu);
		setJMenuBar(jMenuBar);

		usernameButton = new JButton("Username");
		startgameButton = new JButton("Start Game");
		createServerButton = new JButton("Create");
		joinButton = new JButton("Join");
		exitButton = new JButton("Exit");
		findServerButton = new JButton("Find Server");
		
		usernameButton.setToolTipText("change username");
		startgameButton.setToolTipText("start the game");
		createServerButton.setToolTipText("create server");
		joinButton.setToolTipText("join the server");
		
		toolBar.add(createServerButton);
		toolBar.add(joinButton);
		toolBar.addSeparator();
		toolBar.add(usernameButton);
		toolBar.add(startgameButton);
		toolBar.addSeparator();
		toolBar.add(exitButton);
		toolBar.addSeparator();
		toolBar.add(findServerButton);
		contentPane.add(toolBar, BorderLayout.NORTH);


		usernameButton.setEnabled(true);
		startgameButton.setEnabled(false);

		userNameItem.addActionListener(this);
		startgameItem.addActionListener(this);
		exitItem.addActionListener(this);
		userItem.addActionListener(this);
		joinItem.addActionListener(this);
		helpItem.addActionListener(this);

		usernameButton.addActionListener(this);
		startgameButton.addActionListener(this);
		createServerButton.addActionListener(this);
		joinButton.addActionListener(this);
		exitButton.addActionListener(this);
		findServerButton.addActionListener(this);


		messageShow = new JTextArea();
		messageShow.setEditable(false);
		memberShow = new JTextArea();
		memberShow.setEditable(false);

		
		messageScrollPane = new JScrollPane(messageShow,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		messageScrollPane.setPreferredSize(new Dimension(300, 400));
		messageScrollPane.revalidate();
		
		memberScrollPane = new JScrollPane(memberShow,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		memberScrollPane.setPreferredSize(new Dimension(150, 400));
		memberScrollPane.revalidate();

		clientMessage = new JTextField(23);
		clientMessage.setEnabled(true);
		clientMessageButton = new JButton();
		clientMessageButton.setText("Send");

		clientMessage.addActionListener(this);
		clientMessageButton.addActionListener(this);

		messageLabel = new JLabel("Msg sent:");
		downPanel = new JPanel();
		girdBag = new GridBagLayout();
		downPanel.setLayout(girdBag);

		girdBagCon = new GridBagConstraints();
		girdBagCon.gridx = 0;
		girdBagCon.gridy = 0;
		girdBagCon.gridwidth = 5;
		girdBagCon.gridheight = 2;
		girdBagCon.ipadx = 5;
		girdBagCon.ipady = 5;
		nameLabel = new JLabel("User Name: " + userName);
		girdBag.setConstraints(nameLabel, girdBagCon);
		downPanel.add(nameLabel);

		girdBagCon = new GridBagConstraints();
		girdBagCon.gridx = 0;
		girdBagCon.gridy = 3;
		girdBag.setConstraints(messageLabel, girdBagCon);
		downPanel.add(messageLabel);

		girdBagCon = new GridBagConstraints();
		girdBagCon.gridx = 1;
		girdBagCon.gridy = 3;
		girdBagCon.gridwidth = 3;
		girdBagCon.gridheight = 1;
		girdBag.setConstraints(clientMessage, girdBagCon);
		downPanel.add(clientMessage);

		girdBagCon = new GridBagConstraints();
		girdBagCon.gridx = 4;
		girdBagCon.gridy = 3;
		girdBag.setConstraints(clientMessageButton, girdBagCon);
		downPanel.add(clientMessageButton);

		showStatus = new JTextField(35);
		showStatus.setEditable(false);
		girdBagCon = new GridBagConstraints();
		girdBagCon.gridx = 0;
		girdBagCon.gridy = 5;
		girdBagCon.gridwidth = 5;
		girdBag.setConstraints(showStatus, girdBagCon);
		downPanel.add(showStatus);
		
		midPanel = new JPanel();
		midPanel.setLayout(new javax.swing.BoxLayout(midPanel, javax.swing.BoxLayout.LINE_AXIS));
		midPanel.add(memberScrollPane);
		midPanel.add(Box.createRigidArea(new Dimension(10, 0)));

		midPanel.add(messageScrollPane);
		
		//contentPane.add(memberShow, BorderLayout.WEST);
		contentPane.add(midPanel, BorderLayout.CENTER);
		contentPane.add(downPanel, BorderLayout.SOUTH);
		

		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if (type == 1) {
					//DisConnect();
				}
				System.exit(0);
			}
		});
	}

	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();

		if (obj == userItem || obj == createServerButton) {
			server = new TCPNetworkEngine(port);
			server.createServer("demoServer");
			joinButton.setEnabled(false);
			
			ServerThread thread = new ServerThread(this, server);
			thread.start();
		} else if (obj == joinItem || obj == joinButton) {
			o = new TCPNetworkEngine(8999); 
			//o.connect("127.0.0.1");
			List<ConnectInfo> result = o.search();
			if (result.size() == 0)
				JOptionPane.showMessageDialog(null,  "ServerNotFound", "Alert",JOptionPane.ERROR_MESSAGE); 
			else{
				String[] foundServer = new String[result.size()];
				for (int i = 0; i < result.size(); i++)
					foundServer[i] = result.get(i).getIPaddress();
				Object selectedValue = JOptionPane.showInputDialog(null,
			            "Choose one Server", "Input",
			            JOptionPane.INFORMATION_MESSAGE, null,
			            foundServer, foundServer[0]);
				o.connect((String)selectedValue);
			}
		} else if (obj == userNameItem || obj == usernameButton) {

			UserConf userConf = new UserConf(this, userName);
			userConf.setVisible(true);
			userName = userConf.userInputName;
			nameLabel.setText("User Name: " + userName);
			
		} else if (obj == startgameItem || obj == startgameButton) { 

		} else if (obj == clientMessage || obj == clientMessageButton) { 
			String message = clientMessage.getText();
			if(message.startsWith("end")){
				o.disconnect();
			}
			else{
				o.send(message);
			}

		} else if (obj == exitButton || obj == exitItem) { 
			int j = JOptionPane.showConfirmDialog(this, "Confirm exit?", "exit",
					JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE);

			if (j == JOptionPane.YES_OPTION) {
				if (type == 1) {
					//DisConnect();
				}
				System.exit(0);
			}
		} else if (obj == helpItem) {


		} else if (obj == findServerButton) {
			
		}
	}

	public static void main(String[] args) {
		MainGUI app = new MainGUI();
	}
}